package com.rpc.netty.groupChartNetty;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author 何章怀晓 hezhanghuaixiao
 * @version V1.0
 * @desc
 */
public class GroupChartServerHandler extends SimpleChannelInboundHandler<String> {

  //定义一个channel集合   GlobalEventExecutor.INSTANCE是全局单例的事件执行器
  private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);


  SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


  //连接完毕后马上调用
  //将当前客户端channel加入到channelGroup里
  @Override
  public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
    Channel channel = ctx.channel();
    channelGroup.writeAndFlush(
        "[客户端]" + simpleDateFormat.format(new Date()) + "-------" + ctx.channel().remoteAddress()
            + "加入了群聊......\n");
    channelGroup.add(channel);
  }


  //表示断开连接调用
  @Override
  public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
    System.out.println(
        "[客户端]"+simpleDateFormat.format(new Date()) + "---------" + ctx.channel().remoteAddress()
            + "断开连接了......\n");
  }

  //表示用户上线  用户处于活动状态调用
  @Override
  public void channelActive(ChannelHandlerContext ctx) throws Exception {
    System.out.println(
        "客户端"+simpleDateFormat.format(new Date()) + "------------" + ctx.channel().remoteAddress()
            + "上线了.......\n");

  }

  //用户非活动状态调用
  @Override
  public void channelInactive(ChannelHandlerContext ctx) throws Exception {

    System.out.println(simpleDateFormat.format(new Date()) +"----------------"+ctx.channel().remoteAddress() + "下线了.......\n");

  }


  //读取数据
  @Override
  protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
    Channel channel = ctx.channel();

    for (Channel item : channelGroup
    ) {
      //排除自己
      if (channel != item) {
        //直接写到每个socket对应缓冲区
        item.writeAndFlush(
            channel.remoteAddress() + "client发出的消息:" + msg + "由服务器广播给：" + item.remoteAddress());
      } else {
        channel.writeAndFlush("自己发送的消息" + msg + "IP地址为：" + channel.remoteAddress());
      }
    }

  }

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    cause.printStackTrace();
    ctx.close();
  }
}
